package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.ClassesConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysDataProperty;
import com.ruoyi.system.domain.SysObjectProperty;
import com.ruoyi.system.domain.SysRoleClasses;
import com.ruoyi.system.protocol.IDynamicCacheService;
import com.ruoyi.system.protocol.IDynamicDataService;
import com.ruoyi.system.protocol.IDynamicSearchService;
import com.ruoyi.system.protocol.IDynamicTableService;
import com.ruoyi.system.service.ISysDataPropertyService;
import com.ruoyi.system.service.ISysObjectPropertyService;
import com.ruoyi.system.service.ISysRoleClassesService;
import com.ruoyi.web.controller.resourcepool.BaseRetrievalController;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysClasses;
import com.ruoyi.system.service.ISysClassesService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.PostConstruct;

/**
 * 类管理Controller
 * 
 * @author ruoyi
 * @date 2021-10-31
 */
@RestController
@RequestMapping("/system/classes")
public class SysClassesController extends BaseController
{
    @Autowired
    private ISysClassesService sysClassesService;

    @Autowired
    private IDynamicTableService dynamicTableService;

    @Autowired
    private IDynamicDataService dynamicDataService;

    @Autowired
    private IDynamicCacheService dynamicCache;

    @Autowired
    private IDynamicSearchService dynamicSearchService;

    @Autowired
    private ISysDataPropertyService sysDataPropertyService;

    @Autowired
    private ISysObjectPropertyService sysObjectPropertyService;

    @Autowired
    private ISysRoleClassesService sysRoleClassesService;

    private static final Logger LOGGER = LoggerFactory.getLogger(SysClassesController.class);


    @PostConstruct
    public void init() {
        long start = System.currentTimeMillis();
        LOGGER.info("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓初始化刷新资源个数开始↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
//        refresh();
        long end = System.currentTimeMillis();
        LOGGER.info("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑初始化刷新资源个数结束耗时:["+(end-start)+"]↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
    }

    /**
     * 刷新资源数
     */
    @PreAuthorize("@ss.hasPermi('system:classes:list')")
    @GetMapping("/refreshClassesResourceCount")
    public AjaxResult refreshClassesResourceCount()
    {
        refresh();
        return AjaxResult.success();
    }

    //刷新资源数
    private void refresh() {
        List<SysClasses> sysClassesList = sysClassesService.selectSysClassesList(null);
        SysClasses updateClasses = null;
        for (SysClasses sysClasses : sysClassesList) {
            updateClasses = new SysClasses();
            Long dynamicCount = dynamicDataService.getDynamicDataCount(sysClasses.getNameEn(), null);
            if(!dynamicCount.equals(sysClasses.getResourceCount())){
                updateClasses.setId(sysClasses.getId());
                updateClasses.setResourceCount(dynamicCount==null?0:dynamicCount);
                sysClassesService.updateSysClasses(updateClasses);
            }
        }
    }


    /**
     * 查询类管理列表
     */
    @DataScope(filterType = "dynamic")
    @PreAuthorize("@ss.hasPermi('system:classes:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysClasses sysClasses)
    {
        startPage();
        boolean isAdmin = false;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser))
        {
            SysUser currentUser = loginUser.getUser();
            //如果是超级管理员, 则不需要重新查询数据
            if (StringUtils.isNotNull(currentUser) && currentUser.isAdmin()){
                isAdmin = true;
            }
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()){
                List<SysRole> roles = loginUser.getUser().getRoles();
                if(roles.size() > 0){
                    List<Long> roleIdList = roles.stream().map(x -> x.getRoleId()).collect(Collectors.toList());
                    List<SysRoleClasses> roleClassesList = sysRoleClassesService.list(new LambdaQueryWrapper<SysRoleClasses>()
                            .select(SysRoleClasses::getClassesId, SysRoleClasses::getRoleId)
                            .eq(SysRoleClasses::getType, "role").in(SysRoleClasses::getRoleId, roleIdList));
                    String classesIds = roleClassesList.stream().map(x -> x.getClassesId() + "").distinct().collect(Collectors.joining(","));
                    sysClasses.setIdIn(classesIds);
                }else{
                    sysClasses.setIdIn("0");
                }
            }
        }
        List<SysClasses> list = sysClassesService.selectSysClassesList(sysClasses);
        if(!isAdmin){
            HashMap<String, Object> conditon = new HashMap<>();
            dataRangeFiltering(sysClasses.getParams(), conditon);
            for (SysClasses classes : list) {
                Long dynamicDataCount = dynamicDataService.getDynamicDataCount(classes.getNameEn(), conditon);
                classes.setResourceCount(dynamicDataCount);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出类管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:classes:export')")
    @Log(title = "类管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysClasses sysClasses)
    {
        List<SysClasses> list = sysClassesService.selectSysClassesList(sysClasses);
        ExcelUtil<SysClasses> util = new ExcelUtil<SysClasses>(SysClasses.class);
        return util.exportExcel(list, "类管理数据");
    }

    /**
     * 获取类管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:classes:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(sysClassesService.selectSysClassesById(id));
    }

    /**
     * 新增类管理
     */
    @PreAuthorize("@ss.hasPermi('system:classes:add')")
    @Log(title = "类管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysClasses sysClasses)
    {
        dynamicTableService.createTable(sysClasses.getNameEn(), sysClasses.getNameZh());
        int i = sysClassesService.insertSysClasses(sysClasses);
        dynamicCache.refreshClassesListByCache();
        return toAjax(i);
    }

    /**
     * 修改类管理
     */
    @PreAuthorize("@ss.hasPermi('system:classes:edit')")
    @Log(title = "类管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysClasses sysClasses)
    {
        int i = sysClassesService.updateSysClasses(sysClasses);
        dynamicCache.refreshClassesListByCache();
        return toAjax(i);
    }

    /**
     * 删除类管理
     */
    @PreAuthorize("@ss.hasPermi('system:classes:remove')")
    @Log(title = "类管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        delClassData(ids);
        delClassRelation(ids);
        SysObjectProperty sysObjectProperty = null;
        List<SysObjectProperty> sysObjectPropertiesList = null;
        for (Long id : ids) {
            SysClasses sysClasses = sysClassesService.selectSysClassesById(id);

            //删除关联表
            sysObjectProperty = new SysObjectProperty();
            sysObjectProperty.setClassesId(id);
            sysObjectPropertiesList = sysObjectPropertyService.selectSysObjectPropertyList(sysObjectProperty);
            for (SysObjectProperty objectProperty : sysObjectPropertiesList) {
                String opClassesEn = sysClasses.getNameEn()+"_"+objectProperty.getField();
                sysObjectPropertyService.deleteSysObjectPropertyById(objectProperty.getId());
                dynamicTableService.deleteTable(opClassesEn);
            }
            //删除资源表
            dynamicTableService.deleteTable(sysClasses.getNameEn());
            sysClassesService.deleteSysClassesById(id);
        }
        dynamicCache.refreshClassesListByCache();
        return toAjax(1);
    }

    private void delClassRelation(Long[] ids){
        SysDataProperty sysDataProperty = null;
        for (Long id : ids) {
            sysDataProperty = new SysDataProperty();
            sysDataProperty.setClassesId(id);
            List<SysDataProperty> dataPropertyList = sysDataPropertyService.selectSysDataPropertyList(sysDataProperty);
            for (SysDataProperty dataProperty : dataPropertyList) {
                sysDataPropertyService.deleteSysDataPropertyById(dataProperty.getId());
            }
        }
    }

    private void delClassData(Long[] ids){
        for (Long id : ids) {
            SysClasses sysClasses = sysClassesService.selectSysClassesById(id);
            QueryBuilder delQuery = QueryBuilders.termQuery("type", sysClasses.getNameEn());
            dynamicSearchService.deleteQueryDocument(ClassesConstants.ELASTICSEARCH_INDEXES, delQuery);
        }
    }
}
